package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.TbDetail;
import com.bwie.domain.TbOrder;
import com.bwie.domain.TbProduct;
import com.bwie.mapper.TbDetailMapper;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.state.PayStateEnum;
import com.bwie.utils.R;
import com.bwie.vo.OrderVo;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.WeekAmountVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2024-09-26 14:54:20
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbDetailMapper tbDetailMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public R addOrder(OrderVo orderVo) {
        //--1 生成订单
        TbOrder tbOrder = new TbOrder();
        Long orderNo = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(orderNo);

        // 获取用户ID
        tbOrder.setUserId(orderVo.getUserId());

        ArrayList<TbProduct> tbProducts = orderVo.getTbProducts();

        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0.00);
        for (TbProduct tbProduct : tbProducts) {
            totalAmount = totalAmount.add(tbProduct.getProdPrice());
        }
        tbOrder.setOrderAmount(totalAmount);

        tbOrder.setOrderName(tbProducts.get(0).getProdName() + "等商品...");
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());
        tbOrder.setOrderStatus(PayStateEnum.UNPAID.getCode());

        // 把订单保存到数据库
        tbOrderMapper.insert(tbOrder);

        //--2 生成订单明细（使用openFeign，实现下订单）
        TbDetail tbDetail = new TbDetail();
        for (TbProduct tbProduct : tbProducts) {
            tbDetail.setOrderId(tbOrder.getOrderId());
            tbDetail.setProdId(tbProduct.getProdId());
            tbDetail.setProdName(tbProduct.getProdName());
            tbDetail.setProdCount(1);
            tbDetail.setProdPrice(tbProduct.getProdPrice());
            tbDetail.setOrderAmount(tbProduct.getProdPrice());

            tbDetailMapper.insert(tbDetail);
        }

        return R.OK();
    }

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        //-- 构造分页
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //-- 根据Token，获取用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        //-- 根据用户ID，查询订单列表
        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page,
                new QueryWrapper<TbOrder>().lambda().eq(TbOrder::getUserId, userId)
        );

        return R.OK(tbOrderPage);
    }

    @Override
    public R getAmountByLastWeek() {
        //-- 获取数据
        List<WeekAmountVo> amountByLastWeek = tbOrderMapper.getAmountByLastWeek();

        //-- 数据转换
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Double> amounts = new ArrayList<>();
        ArrayList<HashMap> hashMaps = new ArrayList<>();

        for (WeekAmountVo weekAmountVo : amountByLastWeek) {
            names.add(weekAmountVo.getMdate());
            amounts.add(weekAmountVo.getAmount());

            HashMap<String, Object> data = new HashMap<>();
            data.put("name", weekAmountVo.getMdate());
            data.put("value", weekAmountVo.getAmount());
            hashMaps.add(data);
        }

        //-- 返回数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("names", names);
        map.put("list", amounts);
        map.put("pie", hashMaps);

        return R.OK(map);
    }
}




